package com.app.broadcastservicetest;

import com.app.boardcastservicetest.R;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

	private Button start;
	private Button stop;
	private Intent intent = null;
	private static final String MYACTION = "com.app.boardcast";
	private static final int ERROR = 999;
	private static final String TAG = "MainActivity";
	private ProgressBar progressBar;
	private TextView textView;
	private int curLoad = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		start = (Button)findViewById(R.id.start_Btn);
		stop = (Button)findViewById(R.id.stop_Btn);
		progressBar = (ProgressBar)findViewById(R.id.myProgressBar);
		textView = (TextView)findViewById(R.id.loading_Tv);
		
		//点击开始
		start.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
			}
		});
		
		//停止
		stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	protected void onResume() {
		super.onResume();
		Log.i(TAG, "register the broadcast receiver...");
		IntentFilter filter = new IntentFilter(MYACTION);
		registerReceiver(receiver, filter);
	};
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "unregister the broadcast receiver...");
		unregisterReceiver(receiver);
	}



	//handler 更新ui
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Log.i(TAG, "set progress" + curLoad);
			if(curLoad<0||curLoad>100){
				Log.e(TAG, "Error" + curLoad);
				return ;
			}
			progressBar.setProgress(curLoad);
			textView.setText("%"+curLoad);
		}
		
	};
	
	//广播接收器
	BroadcastReceiver receiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if(MYACTION.equals(intent.getAction())){
				Log.i(TAG, "get data from service...");
				curLoad = intent.getIntExtra("currentLoading", ERROR);
				mHandler.sendMessage(mHandler.obtainMessage());
			}
		}
	};
	
}
